﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using AdminApp.Resources;

namespace AdminApp.Controls
{
    public partial class SaveAndRejectControl : UserControl
    {
        public SaveAndRejectControl()
        {
            InitializeComponent();

            if (DesignerProperties.IsInDesignTool)
            {
                _reject.Content = ApplicationStrings.RejectChanges;
                _save.Content = ApplicationStrings.SaveChanges;

                return;
            }

            this.Loaded += (s, e) =>
                {
                    var help = this.Parent as FrameworkElement;
                    bool isPage = false;
                    while (help != null)
                    {
                        if (help is Page)
                        {
                            isPage = true;
                            break;
                        }
                        help = help.Parent as FrameworkElement;
                    }
                    if (isPage)
                    {
                        // Active Navigation Support
                        Page p = help as Page;
                        p.NavigationService.Navigating += (s1, e1) =>
                            {
                                DomainDataSource dds = this.DataContext as DomainDataSource;
                                if (dds != null)
                                {
                                    if (dds.HasChanges)
                                    {
                                        if (MessageBox.Show(ApplicationStrings.DropUnsavedChanges, ApplicationStrings.MessageBoxQuestionHeader, MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                                        {
                                            e1.Cancel = true;
                                        }
                                    }
                                }
                            };
                    }
                };
        }

        private void _save_Click(object sender, RoutedEventArgs e)
        {
            DomainDataSource dds = this.DataContext as DomainDataSource;
            if (dds != null)
            {
                dds.SubmitChanges();
            }
        }

        private void _reject_Click(object sender, RoutedEventArgs e)
        {
            DomainDataSource dds = this.DataContext as DomainDataSource;
            if (dds != null)
            {
                dds.RejectChanges();
            }
        }

    }
}
